package service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import play.data.validation.Required;
import play.db.jpa.JPA;

import models.Handshake;
import models.Notification;
import models.User;

public class NotificationManager {
	
	public void AddNewNotification(User user, String message, String link) throws Exception{
		if (user.id == null) throw new Exception("User model should be persisted before passing to NotificationManager.");
		Notification notification = new Notification();
		notification.user = user;
		notification.message = message;
		notification.link = link;
		notification.isread = false;
		notification.save();
	}
	
	public List<Notification> GetNotifications(Long user_id){
		Query query = JPA.em().createQuery("from " + Notification.class.getName() + " where user_id=" + user_id + "order by id desc");
		List<Notification> notifications = query.getResultList();
		return notifications;
	}
	
	public void SetNotificationAsRead(int notificationID)
	{
		Query query = JPA.em().createQuery("from " + Notification.class.getName() + " where id=" + notificationID);
		Notification notification = (Notification) query.getResultList().get(0);
		notification.isread = true;
		notification.save();
	}
	public void SetAllUserNotificationsAsRead(User user)
	{
		String queryStr = "UPDATE Notification n SET n.isread = true WHERE n.user.id = " + user.id;
		Query query = JPA.em().createQuery(queryStr);
		query.executeUpdate();
	}
	
	public List<Notification> ExtractUnreadNotifications(List<Notification> allNotifications){
		List<Notification> unreadNotifications = null;
		unreadNotifications = new ArrayList<Notification>();
		for (Notification notification : allNotifications) {
			if (!notification.isread) unreadNotifications.add(notification);
		}
		return unreadNotifications;
	}
	
}
